package com.example.shop.detail

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.base.entity.DetailEntityResult
import com.example.base.entity.ResultEntity
import com.example.base.mvvm.BaseViewModel
import com.google.gson.Gson
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody

class DetailViewModel:BaseViewModel() {
    val detailSuccess = MutableLiveData<DetailEntityResult>()
    val detailFail = MutableLiveData<String>()

    fun detail(goodsId:Int){
        viewModelScope.launch {
            try {
                val result = apiServer.detail(goodsId)
                detailSuccess.value = result
            }catch (e:Exception){
                detailFail.value = e.message
            }
        }
    }

    val addSuccess = MutableLiveData<ResultEntity>()
    val addFail = MutableLiveData<String>()
    fun addCar(goodsId:Int,count:Int){
        viewModelScope.launch {
            try {
                val map = mutableMapOf<String,Int>()
                map["goods_id"] = goodsId
                map["count"] = count
                val json = Gson().toJson(map)
                val body = RequestBody.create("application/json;charset=utf-8".toMediaTypeOrNull(),json)
                val result = apiServer.addCar(body)
                addSuccess.value = result
            }catch (e:Exception){
                addFail.value = e.message
            }

        }
    }
}